package leetcode.offer_two_special.queue;

import leetcode.tree.common.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author mazouri
 * @create 2021-09-11 19:48
 */
public class _45_findBottomLeftValue {
    public int findBottomLeftValue1(TreeNode root) {
        int current = 0;
        int next = 0;
        Queue<TreeNode> queue = new LinkedList<>();

        if (root != null) {
            queue.offer(root);
            current = 1;
        }

        int bottomLeft = root.val;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            current--;

            if (node.left != null) {
                queue.offer(node.left);
                next++;
            }

            if (node.right != null) {
                queue.offer(node.right);
                next++;
            }

            if (current == 0) {
                current = next;
                next = 0;
                if (!queue.isEmpty()) bottomLeft = queue.peek().val;
            }
        }
        return bottomLeft;
    }

    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            root = queue.poll();
            if (root.right != null) queue.offer(root.right);
            if (root.left != null) queue.offer(root.left);
        }
        return root.val;
    }
}
